package cn.loioi.util.page;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.loioi.util.RequestUtil;
import cn.loioi.util.page.query.where.QueryGroup;
import cn.loioi.util.page.query.where.QueryRule;

/**
 * JqGrid分页组件
 * @file_name :JqGrid.java
 * @author :loioi.cn
 * @创建时间 :2016年10月31日 上午11:32:44
 */
public class JqGrid<T> extends PageUtil {
	private static final long serialVersionUID = 724174294475227580L;

	public JqGrid(HttpServletRequest request) {
		// 获取基本分页属性
		this.setPageNo(RequestUtil.getValueInt(request, "page", 1));
		this.setPageSize(RequestUtil.getValueInt(request, "rows", 20));
		// 获取排序属性
		this.sort(RequestUtil.getValueStr(request, "sidx", null)).direction(RequestUtil.getValueStr(request, "sord"));
		// 获取查询条件
		if (RequestUtil.getValueBoolean(request, "_search", false)) {
			// 判断是不是简单查询条件模式
			String feild = RequestUtil.getValueStr(request, "searchField");
			if (StringUtils.isNotEmpty(feild)) {// 是
				this.addQueryFilter(feild, QueryRule.pasre(RequestUtil.getValueStr(request, "searchOper")), RequestUtil.getValueStr(request, "searchString"));
			} else {// 不是
				this.parseFilter(RequestUtil.getValueStr(request, "filters"));
			}
		}
	}

	private void parseFilter(String queryJSON) {
		// 转为json对象
		JSONObject json = JSONObject.parseObject(queryJSON);
		if (json == null || json.isEmpty()) return;
		// 获取查询条件的连接关系
		QueryGroup queryGroup = QueryGroup.pasre(json.getString("groupOp"));
		// 获取所有的条件
		JSONArray rules = json.getJSONArray("rules");
		if (rules == null) return;
		for (Object object : rules) {
			if (object instanceof JSONObject) {
				JSONObject obj = (JSONObject) object;
				this.addQueryFilter(queryGroup, obj.getString("field"), QueryRule.pasre(obj.getString("op")), obj.getString("data"));
			}
		}
	}
}
